﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Quizz.Library.Helper
{
    public class JsonNetResult : JsonResult
    {
        public JsonNetResult(){}

        public JsonNetResult(object responseBody)
        {
            Data = responseBody;
        }

        public JsonNetResult(object responseBody, JsonSerializerSettings settings)
            :this (responseBody)
        {
            Settings = settings;
        }

        public JsonNetResult(object responseBody, bool allowGet)
            :this(responseBody)
        {
            JsonRequestBehavior = allowGet ? JsonRequestBehavior.AllowGet : JsonRequestBehavior.DenyGet;
        }

        public JsonNetResult(object responseBody, bool allowGet, JsonSerializerSettings settings)
            : this(responseBody, allowGet)
        {
            Settings = settings;
        }

        #region Property

        public JsonSerializerSettings Settings { get; set; }

        private Formatting Formatting
        {
            get { return Debugger.IsAttached ? Formatting.Indented : Formatting.None; }
        }

        #endregion

        #region Methods

        /// <summary> 
        /// Serialises the response and writes it out to the response object 
        /// </summary> 
        /// <param name="context">The execution context</param> 
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if(Settings == null)
            {
                Settings = new JsonSerializerSettings();
            }
            if (Settings.Converters == null)
                Settings.Converters = new List<JsonConverter>();
            if (!Settings.Converters.Any(a => a is JavaScriptDateTimeConverter))
            {
                Settings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy HH:mm:ss" });
            }

            var response = context.HttpContext.Response;

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                context.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.CurrentCultureIgnoreCase))
            {
                throw new InvalidOperationException("Request methods is not allowed !");
            }


            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

            response.ContentEncoding = ContentEncoding ?? Encoding.UTF8;

            if (Data != null)
                response.Write(JsonConvert.SerializeObject(Data, Formatting, Settings));
        }

        #endregion
    }
}
